#ifndef __MY_CLIENT__
#define __MY_CLIENT__

#include <iostream>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace wzh
{
    class udpclient
    {
    private:
        int _sock;
        std::string _ip;
        uint16_t _port;

    public:
        udpclient(std::string ip, int port) : _ip(ip), _port(port)
        {
        }
        void initServer()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cout << "create socket fail\n";
                exit(-1);
            }
            std::cout << "create socket success\n";
        }
        void start()
        {
            struct sockaddr_in server_addr;
            bzero(&server_addr, sizeof(server_addr));
            server_addr.sin_addr.s_addr = inet_addr(_ip.c_str());
            server_addr.sin_family = AF_INET;
            server_addr.sin_port = htons(_port);
            while (1)
            {
                char buffer[1024];
                std::cout << "input-># ";
                fgets(buffer, sizeof(buffer), stdin);

                int ret = sendto(_sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
                if (ret > 0)
                {
                    char buffer[2048];
                    struct sockaddr_in temp;
                    socklen_t len = sizeof(temp);
                    int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "recv " << buffer << std::endl;
                    }
                    else 
                    {
                        std::cout << "recv fail\n";
                    }
                }
                else
                {
                    std::cout << "sendto fail\n";
                    break;
                }
            }
        }
        ~udpclient()
        {
        }
    };
}

#endif